<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(A卷,100分)- 等和子数组最小和（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>给定一个数组nums&#xff0c;将元素分为若干个组&#xff0c;使得每组和相等&#xff0c;求出满足条件的所有分组中&#xff0c;组内元素和的最小值。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>第一行输入 m<br /> 接着输入m个数&#xff0c;表示此数组nums<br /> 数据范围&#xff1a;1&lt;&#61;m&lt;&#61;50, 1&lt;&#61;nums[i]&lt;&#61;50</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>最小拆分数组和</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">7<br /> 4 3 2 3 5 2 1</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">5</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;"> <p>可以等分的情况有&#xff1a;</p> <p>4 个子集&#xff08;5&#xff09;&#xff0c;&#xff08;1,4&#xff09;&#xff0c;&#xff08;2,3&#xff09;&#xff0c;&#xff08;2,3&#xff09;</p> <p>2 个子集&#xff08;5, 1, 4&#xff09;&#xff0c;&#xff08;2,3, 2,3&#xff09;</p> <p>但最小的为5。</p> </td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>本题算是<a href="https://blog.csdn.net/qfc_128220/article/details/127761308?csdn_share_tail&#61;%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22127761308%22%2C%22source%22%3A%22qfc_128220%22%7D" title="LeetCode - 698 划分为k个相等的子集_伏城之外的博客-CSDN博客">LeetCode - 698 划分为k个相等的子集_伏城之外的博客-CSDN博客</a></p> 
<p>的变种题&#xff0c;本题同样是要将数组划分为k个和相等的子集。</p> 
<p></p> 
<p>本题要我们求解&#xff1a;最小拆分数组和&#xff0c;其实就是求解&#xff1a;最小子集和&#xff0c;其实就是求解&#xff0c;最大k值。因为k值越大&#xff0c;则对应的子集的和越小。</p> 
<p></p> 
<p>这里k的求解很简单&#xff0c;首先&#xff0c;我们可以猜想下k的上限是多少&#xff1f;</p> 
<p>比如数组所有元素都相等&#xff0c;则k &#61;&#61;&#61; m&#xff0c;即每个元素都能作为一个子集&#xff0c;因此我们可以让k从m开始尝试&#xff0c;如果不行&#xff0c;则k--&#xff0c;直到k&#61;1。</p> 
<p></p> 
<p>而验证nums是否可以划分为k层&#xff0c;其实就是判断nums是否可以划分为k个和相等的子集&#xff0c;这个判断逻辑可以复用<a href="https://blog.csdn.net/qfc_128220/article/details/127761308?csdn_share_tail&#61;%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22127761308%22%2C%22source%22%3A%22qfc_128220%22%7D" title="LeetCode - 698 划分为k个相等的子集_伏城之外的博客-CSDN博客">LeetCode - 698 划分为k个相等的子集_伏城之外的博客-CSDN博客</a></p> 
<p>中的逻辑。</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 2) {
    const m &#61; parseInt(lines[0]);
    const arr &#61; lines[1].split(&#34; &#34;).map(Number);

    console.log(getResult(arr, m));

    lines.length &#61; 0;
  }
});

function getResult(arr, m) {
  const sum &#61; arr.sort((a, b) &#61;&gt; b - a).reduce((p, c) &#61;&gt; p &#43; c);

  while (m) {
    if (canPartitionMSubsets([...arr], sum, m)) return sum / m;
    m--;
  }

  return sum;
}

function canPartitionMSubsets(arr, sum, m) {
  if (sum % m !&#61;&#61; 0) return false;

  const subSum &#61; sum / m;

  if (subSum &lt; arr[0]) return false;

  while (arr[0] &#61;&#61;&#61; subSum) {
    arr.shift();
    m--;
  }

  const buckets &#61; new Array(m).fill(0);

  return partition(arr, 0, buckets, subSum);
}

function partition(arr, index, buckets, subSum) {
  if (index &#61;&#61;&#61; arr.length) return true;

  const select &#61; arr[index];

  for (let i &#61; 0; i &lt; buckets.length; i&#43;&#43;) {
    if (i &gt; 0 &amp;&amp; buckets[i] &#61;&#61;&#61; buckets[i - 1]) continue;
    if (select &#43; buckets[i] &lt;&#61; subSum) {
      buckets[i] &#43;&#61; select;
      if (partition(arr, index &#43; 1, buckets, subSum)) return true;
      buckets[i] -&#61; select;
    }
  }

  return false;
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<p>感谢m0_71826536指正41行错误&#xff0c;41行在用例</p> 
<blockquote> 
 <p>5</p> 
 <p>5 5 5 5 5</p> 
</blockquote> 
<p>时会出现越界异常</p> 
<pre><code class="language-java">import java.util.LinkedList;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int m &#61; sc.nextInt();

    LinkedList&lt;Integer&gt; link &#61; new LinkedList&lt;&gt;();
    for (int i &#61; 0; i &lt; m; i&#43;&#43;) {
      link.add(sc.nextInt());
    }

    System.out.println(getResult(link, m));
  }

  public static int getResult(LinkedList&lt;Integer&gt; link, int m) {
    link.sort((a, b) -&gt; b - a);

    int sum &#61; 0;
    for (Integer ele : link) {
      sum &#43;&#61; ele;
    }

    while (m &gt; 0) {
      LinkedList&lt;Integer&gt; link_cp &#61; new LinkedList&lt;&gt;(link);
      if (canPartitionMSubsets(link_cp, sum, m)) return sum / m;
      m--;
    }

    return sum;
  }

  public static boolean canPartitionMSubsets(LinkedList&lt;Integer&gt; link, int sum, int m) {
    if (sum % m !&#61; 0) return false;

    int subSum &#61; sum / m;

    if (subSum &lt; link.get(0)) return false;

    //    while (link.get(0) &#61;&#61; subSum) { // 此段代码可能越界
    while (link.size() &gt; 0 &amp;&amp; link.get(0) &#61;&#61; subSum) {
      link.removeFirst();
      m--;
    }

    int[] buckets &#61; new int[m];
    return partition(link, 0, buckets, subSum);
  }

  public static boolean partition(LinkedList&lt;Integer&gt; link, int index, int[] buckets, int subSum) {
    if (index &#61;&#61; link.size()) return true;

    int select &#61; link.get(index);

    for (int i &#61; 0; i &lt; buckets.length; i&#43;&#43;) {
      if (i &gt; 0 &amp;&amp; buckets[i] &#61;&#61; buckets[i - 1]) continue;
      if (select &#43; buckets[i] &lt;&#61; subSum) {
        buckets[i] &#43;&#61; select;
        if (partition(link, index &#43; 1, buckets, subSum)) return true;
        buckets[i] -&#61; select;
      }
    }

    return false;
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
m &#61; int(input())
link &#61; list(map(int, input().split()))


# 算法入口
def getResult(link, m):
    link.sort(reverse&#61;True)

    sumV &#61; 0
    for ele in link:
        sumV &#43;&#61; ele

    while m &gt; 0:
        if canPartitionMSubsets(link[:], sumV, m):
            return int(sumV / m)
        m -&#61; 1

    return sumV


def canPartitionMSubsets(link, sumV, m):
    if sumV % m !&#61; 0:
        return False

    subSum &#61; sumV / m

    if subSum &lt; link[0]:
        return False

    while len(link) &gt; 0 and link[0] &#61;&#61; subSum:
        link.pop(0)
        m -&#61; 1

    buckets &#61; [0] * m

    return partition(link, 0, buckets, subSum)


def partition(link, index, buckets, subSum):
    if index &#61;&#61; len(link):
        return True

    select &#61; link[index]

    for i in range(len(buckets)):
        if i &gt; 0 and buckets[i] &#61;&#61; buckets[i - 1]:
            continue

        if select &#43; buckets[i] &lt;&#61; subSum:
            buckets[i] &#43;&#61; select
            if partition(link, index &#43; 1, buckets, subSum):
                return True
            buckets[i] -&#61; select

    return False


# 算法调用
print(getResult(link, m))</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>